import React, { useState, useEffect } from 'react'
import { reqgetgoodsinfo,reqcartadd } from '../../http/api'
import { Toast } from 'antd-mobile'
import qs from "qs"
import Header from '../../components/Header/Header'
import "../Detail/Detail.less"

export default function Detail(props) {
  const  [detailList, setdetailList] = useState([])
  useEffect(() => {
    let search = props.location.search;
    let arr = qs.parse(search.slice(1));
    reqgetgoodsinfo({ id: arr.id }).then((res) => {
      setdetailList(res.data.list)
    })
  }, [])
  
  const goshop=(a)=>{
    let {uid} = JSON.parse(sessionStorage.getItem("info"));
    reqcartadd({uid,type:1,goodsid:a,num:1}).then((res)=>{
      if(res.data.code === 200){
        Toast.show(res.data.msg);
        props.history.push("/index/shop")
      }
    })
  }

  return (
    detailList.length > 0 ? <div>
        <Header text="商品详情" back></Header>
        <div className='detailimg'>
          <img src={'http://localhost:1000' + detailList[0].img} alt="" />
        </div>
        <div>{detailList[0].goodsname}</div>
        <div>{detailList[0].description}</div>
        <div>{detailList[0].price}</div>
        <div className='btn' onClick={()=>goshop(detailList[0].id)}>加入购物车</div>
      </div> : null
  )
}

